# Title     : TODO
# Objective : TODO
# Created by: Administrator
# Created on: 2019/6/18

library(data.table)
library(optparse)
library(ropls)
library(magrittr)
library(tidyverse)

option_list <- list(
  make_option("--i", default = "AllMet.csv", type = "character", help = "metabolite data file"),
  make_option("--g", default = "SampleInfo.csv", type = "character", help = "sample group file"),
  make_option("--mc", default = "meta_color.txt", type = "character", help = "metabolite color file"),
  make_option("--sc", default = "sample_color.txt", type = "character", help = "sample color file")
)
opt <- parse_args(OptionParser(option_list = option_list))

sampleInfo <- read.csv(opt$g, header = T, stringsAsFactors = F) %>%
  select(c("SampleID", "ClassNote"))

sampleIds <- sampleInfo %>%
  .$SampleID

data <- read_csv(opt$i) %>%
  select(-c("HMDB", "KEGG", "Metabolite")) %>%
  select(c("Class", sampleIds))

df <- data %>%
  group_by(Class) %>%
  summarise_all(sum) %>%
  gather("SampleID", "Value", -Class) %>%
  spread(Class, "Value") %>%
  left_join(sampleInfo, by = c("SampleID")) %>%
  group_by(ClassNote) %>%
  summarise_at(vars(-"SampleID"), sum) %>%
  gather("Class", "Value", -ClassNote) %>%
  spread(ClassNote, "Value") %>%
  mutate_at(vars(-"Class"), function(x) { x * 100 / sum(x) }) %>%
  gather("Sample", "Value", -Class) %>%
  spread(Class, "Value")

metaColDf <- read_tsv(opt$mc) %>%
  select(c("Class", "col"))
metaCols <- metaColDf %>%
  deframe()

pdf <- df %>%
  gather("Class", "Value", -Sample) %>%
  arrange(desc(Value)) %>%
  mutate(Class = factor(Class, levels = unique(Class)),
         Sample = factor(Sample, levels = unique(sampleInfo$ClassNote)))


outDf <- pdf %>%
  spread(Sample, "Value")

write_csv(outDf, "Class_Barplot_by_Group.csv")

minWidth<-7
width <- minWidth + max(0, length(unique(sampleInfo$ClassNote)) - 2) * 0.1

pdf("Class_Barplot_by_Group.pdf", width = width, height = 5)

yBreaks <- seq(0, 100, by = 25)

print(pdf$Class)
metaCols

pData <- read_csv("Class_Barplot_by_Group_Test.csv") %>%
  rowwise() %>%
  do({
       result <- as_tibble(.)
       p <- result["P"]
       str <- if (p < 0.05 && p >= 0.01) {
         "*"
       }else if (p < 0.01 && p >= 0.001) {
         "**"
       }else if (p < 0.001) "***" else ""
       result$label <- str_c(result$Class, " ", str)
       result
     }) %>%
  ungroup() %>%
  arrange(factor(Class, levels = unique(pdf$Class)))

p <- ggplot(pdf, mapping = aes(x = Sample, y = Value, fill = Class)) +
  xlab("") +
  ylab("Relative Abundance(%)") +
  theme_minimal(base_size = 8.8, base_family = "Times") +
  theme(axis.text.x = element_text(size = 14), panel.grid.minor = element_blank(),
        axis.text.y = element_text(size = 15), legend.position = 'right', panel.grid.major.x = element_blank(),
        panel.grid.major.y = element_line(size = 0.5, colour = "#D8D8D8"),
        panel.border = element_blank(), axis.title.y = element_text(size = 15),
        legend.margin = margin(t = 0.3, b = 0.1, unit = 'cm'), axis.ticks = element_line(colour = "black", size = 0.5),
        legend.text = element_text(size = 8), axis.title.x = element_text(size = 11), legend.key.size = unit(1, "line"),
        axis.line = element_blank(), plot.margin = unit(c(0.5, 0.5, 0.5, 0.5), "cm")
  ) +
  geom_col(width = 0.25) +
  scale_fill_manual("", values = metaCols,labels = pData$label,breaks=pData$Class) +
  scale_y_continuous(breaks = yBreaks)


p

dev.off()
